import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Typography, Button, Spin, message, Table, Tag, Space } from '@/utils/antd-imports';
import { projectApi } from '@/api/projectApi';
import { transformProjectsForCards, getStatusColor, getTypeColor } from '@/utils/projectDataTransform';

const { Title, Text } = Typography;

const ProjectApiTest = () => {
  const [loading, setLoading] = useState(false);
  const [projects, setProjects] = useState([]);
  const [apiStatus, setApiStatus] = useState('未测试');

  // 测试API连接
  const testApiConnection = async () => {
    setLoading(true);
    setApiStatus('测试中...');
    
    try {
      const response = await projectApi.getAllProjects();
      console.log('API响应:', response);
      
      if (response.code === 200) {
        const transformedProjects = transformProjectsForCards(response.data);
        setProjects(transformedProjects);
        setApiStatus('连接成功');
        message.success(`成功获取 ${transformedProjects.length} 个项目数据`);
      } else {
        setApiStatus('API错误: ' + response.message);
        message.error('API返回错误: ' + response.message);
      }
    } catch (error) {
      console.error('API调用失败:', error);
      setApiStatus('连接失败: ' + error.message);
      message.error('API调用失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  // 测试分页查询
  const testPaginationQuery = async () => {
    setLoading(true);
    try {
      const response = await projectApi.getProjectList({
        pageNum: 1,
        pageSize: 5
      });
      console.log('分页查询响应:', response);
      
      if (response.code === 200) {
        message.success('分页查询成功');
      } else {
        message.error('分页查询失败: ' + response.message);
      }
    } catch (error) {
      console.error('分页查询失败:', error);
      message.error('分页查询失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  // 测试状态查询
  const testStatusQuery = async () => {
    setLoading(true);
    try {
      const response = await projectApi.getProjectsByStatus('in_progress');
      console.log('状态查询响应:', response);
      
      if (response.code === 200) {
        message.success('状态查询成功');
      } else {
        message.error('状态查询失败: ' + response.message);
      }
    } catch (error) {
      console.error('状态查询失败:', error);
      message.error('状态查询失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '项目编号',
      dataIndex: 'code',
      key: 'code',
      width: 150,
    },
    {
      title: '项目名称',
      dataIndex: 'project_name',
      key: 'project_name',
      width: 200,
    },
    {
      title: '项目类型',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (type) => (
        <Tag color={getTypeColor(type)}>
          {type}
        </Tag>
      ),
    },
    {
      title: '项目状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => (
        <Tag color={getStatusColor(status)}>
          {status}
        </Tag>
      ),
    },
    {
      title: '项目经理',
      dataIndex: 'manager',
      key: 'manager',
      width: 100,
    },
    {
      title: '创建时间',
      dataIndex: 'createDate',
      key: 'createDate',
      width: 120,
    },
    {
      title: '截止时间',
      dataIndex: 'deadline',
      key: 'deadline',
      width: 120,
    },
    {
      title: '进度',
      dataIndex: 'progress',
      key: 'progress',
      width: 80,
      render: (progress) => `${progress}%`,
    },
  ];

  return (
    <div style={{ padding: 24 }}>
      <Title level={2}>项目API测试页面</Title>
      
      {/* API状态卡片 */}
      <Card style={{ marginBottom: 24 }}>
        <Title level={4}>API连接状态</Title>
        <Space direction="vertical" style={{ width: '100%' }}>
          <Text>当前状态: <Text code>{apiStatus}</Text></Text>
          <Space>
            <Button 
              type="primary" 
              onClick={testApiConnection}
              loading={loading}
            >
              测试获取所有项目
            </Button>
            <Button 
              onClick={testPaginationQuery}
              loading={loading}
            >
              测试分页查询
            </Button>
            <Button 
              onClick={testStatusQuery}
              loading={loading}
            >
              测试状态查询
            </Button>
          </Space>
        </Space>
      </Card>

      {/* 项目数据展示 */}
      {projects.length > 0 && (
        <Card>
          <Title level={4}>项目数据 ({projects.length} 条)</Title>
          <Table
            columns={columns}
            dataSource={projects}
            rowKey="id"
            pagination={{
              pageSize: 10,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条记录`,
            }}
            scroll={{ x: 1000 }}
          />
        </Card>
      )}

      {/* 加载状态 */}
      {loading && (
        <div style={{ 
          display: 'flex', 
          justifyContent: 'center', 
          alignItems: 'center', 
          height: 200 
        }}>
          <Spin size="large" />
        </div>
      )}
    </div>
  );
};

export default ProjectApiTest;
